from datetime import date

from django.views import View
from rest_framework.viewsets import ModelViewSet

from users.models import User
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser

# 用户总量统计
class UserTotalCountView(APIView):
    #管理员权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取所有用户总数
        count = User.objects.all().count()
        return Response({
            'count': count,
            'date': now_date
        })

# 日活跃用户统计
class UserDailyActiveCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取活跃用户总数
        count = User.objects.filter(last_login__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })

# 日下单用户量统计
class UserDailyOrderCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取当日下单用户数量  orders__create_time 订单创建时间
        count = User.objects.filter(orderinfo__create_time__gte=now_date).count()
        return Response({
            "count": count,
            "date": now_date
        })

# 日增用户统计
class UserDailyAddCountView(APIView):
    # 管理员权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取明天日期
        start_date = now_date + timedelta(days=1)
        count = User.objects.filter(date_joined__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })


from datetime import timedelta
# 月增用户统计
class UserMonthCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 获取一个月前日期
        start_date = now_date - timedelta(days=30)
        # 创建空列表保存每天的用户量
        date_list = []

        for i in range(30):
            # 循环遍历获取当天日期
            index_date = start_date + timedelta(days=i)
            # 指定下一天日期
            cur_date = start_date + timedelta(days=i + 1)

            # 查询条件是大于当前日期index_date，小于明天日期的用户cur_date，得到当天用户量
            count = User.objects.filter(date_joined__gte=index_date, date_joined__lt=cur_date).count()

            date_list.append({
                'count': count,
                'date': index_date
            })

        return Response(date_list)


from rest_framework.generics import ListAPIView
from meiduo_admin.serializers.user import UserSerializer, GoodVisitCountSerializer
from meiduo_admin.utils import PageNum
from rest_framework.generics import ListCreateAPIView
# from apps.meiduo_admin.serializers import UserAddSerializer
class UserListView(ListCreateAPIView):

    serializer_class = UserSerializer

    pagination_class = PageNum

    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is '' or keyword is None:
            return User.objects.all()
        else:
            return User.objects.filter(username=keyword)


from django import http
from goods.models import GoodsVisitCount, GoodsCategory



class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        """记录分类商品访问量"""
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code':400,
                                 'errmsg':'缺少必传参数'})

        # 获取今天的日期
        from django.utils import timezone
        today_date=timezone.localdate()
        try:
            # 查询今天该类别的商品的访问量
            counts_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果该类别的商品在今天没有过访问记录，就新建一个访问记录
            counts_data = GoodsVisitCount()

        try:
            counts_data.category = category
            counts_data.count += 1
            counts_data.save()
        except Exception as e:
            return http.HttpResponseServerError('服务器异常')

        return http.JsonResponse({'code': 0, 'errmsg': 'OK'})

# 实现日分类商品访问量
class GoodDayCountView(APIView):
    def get(self, request):
        data = GoodsVisitCount.objects.all()
        ser = GoodVisitCountSerializer(data, many=True)
        return Response(ser.data)
